package com.dodoke.dao.impl;

import com.dodoke.dao.RoleDao;
import com.dodoke.entity.Role;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class RoleDaoImpl implements RoleDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<Role> findAllList() {
        List<Role> roleList = jdbcTemplate.query("select id," +
                "role_name AS roleName," +
                "role_desc AS roleDesc " +
                "from sys_role",new BeanPropertyRowMapper<Role>(Role.class));
        return roleList;
    }

    /**
     * 新增角色
     * @param role
     * @return
     */
    @Override
    public Integer add(Role role) {
        return jdbcTemplate.update("insert into sys_role (role_name,role_desc) values (?,?)", role.getRoleName(),role.getRoleDesc());
    }

    /**
     * 根据用户id来获取用户所拥有的角色
     * @param userId
     * @return
     */
    @Override
    public List<Role> getRoleListByUserId(Integer userId) {
        List<Role> roleList = jdbcTemplate.query("select a.*,r.role_name AS roleName " +
                        "from sys_user_role a  " +
                        "left join sys_role r on r.id = a.role_id " +
                        "where a.user_id = ?  ",
                new BeanPropertyRowMapper<>(Role.class),
                userId);
        return roleList;
    }
}
